package com.boarsoft.rpc.generalize;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.boarsoft.common.util.JsonUtil;

public abstract class RpcGenType implements Serializable {
	private static final long serialVersionUID = 4045708340615424215L;

	protected static Map<String, Class<?>> clazzMap = new ConcurrentHashMap<>();

	protected String clazzName;

	protected Object create(String clazzName)
			throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Class<?> clazz = clazzMap.get(clazzName);
		if (clazz == null) {
			synchronized (clazzMap) {
				clazz = clazzMap.get(clazzName);
				if (clazz == null) {
					clazz = (Class<?>) Class.forName(clazzName);
					clazzMap.put(clazzName, clazz);
				}
			}
		}
		return clazz.newInstance();
	}

	/**
	 * 将泛化对象转为实际对象
	 * 
	 * @return
	 * @throws ClassNotFoundException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	abstract Object specialize() throws ClassNotFoundException, InstantiationException, IllegalAccessException;

	@Override
	public String toString() {
		return JsonUtil.toJSONString(this);
	}

	public String getClazzName() {
		return clazzName;
	}

	public void setClazzName(String clazzName) {
		this.clazzName = clazzName;
	}
}
